package com.yz.group1.group_1.controller;

import com.yz.group1.group_1.entity.MedicalRecord;
import com.yz.group1.group_1.service.MedicalRecordService;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@CrossOrigin
@RestController
@RequestMapping("/medicalRecord")
public class MedicalRecordController {

    @Autowired
    private MedicalRecordService medicalRecordService;

    // 提交诊断结果
    @PostMapping("/save")
    public void saveMedicalRecord(@RequestBody MedicalRecord medicalRecord,
                                  HttpServletResponse response) {
        try {
            System.out.println("接收诊断记录：" + medicalRecord);
            boolean success = medicalRecordService.save(medicalRecord);
            if (!success) {
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "保存失败，数据库操作未执行");
            }
        } catch (Exception e) {
            e.printStackTrace();
            try {
                // 保留异常提示，但不阻断提交（实际是否成功取决于数据库外键约束）
                response.sendError(
                        HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                        "保存失败：" + e.getMessage()
                );
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }
    // 获取诊疗记录列表
    @GetMapping("/list")
    public List<MedicalRecord> listMedicalRecords(@RequestParam(required = false) Long registrationId) {
        return medicalRecordService.listByRegistrationId(registrationId);
    }
}